<script setup lang="ts">
import { requiredCheck, singleIpCheckFun, validatePortFun } from "@/utils/verify";
import { ref, onMounted } from "vue";
import { addData, editData } from "@/api/modules/system/account";
import { cfgList, cfgSetSyscfg, cfgSetSyslog } from "@/api/modules/system/params";
import { ElMessage } from "element-plus";
import { generateUUID } from "@/utils/index";

interface Props {
  title?: string;
  rowData?: Object;
}

const props = withDefaults(defineProps<Props>(), {
  title: "新增账号",
  rowData: undefined
});
defineOptions({
  name: "UpdateForm" // 默认策略
});
import useUpdate from "@/hooks/useUpdate";
import { ifaceAll, ifacemodeUpdate } from "@/api/modules/dynamic-camouflage/line-config";
import BaseButton from "@/components/BaseButton/index.vue";

const emits = defineEmits(["success"]);
const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle } = useUpdate({
  rules: {
    logCfg: [
      {
        validator: (rule, value, callback) => {
          if (updateFormData.logCfg.every(item => !item.port && !item.ip)) {
            callback();
          }
          if (updateFormData.logCfg.some(item => !validatePortFun(item.port) || !singleIpCheckFun(item.ip))) {
            callback(new Error("IP或端口格式错误"));
          }
          callback();
        },
        trigger: "blur"
      }
    ],
    type: [...requiredCheck("请选择日志类型")]
  },
  defaultData: {
    type: [],
    logCfg: [{ ip: "", port: "", id: generateUUID() }]
  }
});
const ifaces = ref([]);

async function getIface() {
  try {
    const res = await ifaceAll();
    console.log(res);
    if (res) {
      ifaces.value = Object.values(res);
      console.log(ifaces.value);
    }
    Object.values(res);
  } catch (error) {}
}

async function submitCb() {
  await submit({
    addApi: addData,
    updateApi: editData,
    sendData: {
      name: updateFormData.name,
      passwordRe: updateFormData.passwordRe || "",
      password: updateFormData.password || "",
      role: updateFormData.role,
      id: updateFormData?.id
    }
  });
  emits("success");
}

function findCombinationForSum(arr, target) {
  const result = [];

  function backtrack(start, currentSum, currentCombination) {
    if (currentSum === target) {
      result.push([...currentCombination]); // 找到组合，保存结果
      return;
    }
    if (currentSum > target) {
      return; // 超过目标和，返回
    }

    for (let i = start; i < arr.length; i++) {
      currentCombination.push(arr[i]); // 选择当前元素
      backtrack(i, currentSum + arr[i], currentCombination); // 继续递归
      currentCombination.pop(); // 回溯，移除当前元素
    }
  }

  backtrack(0, 0, []);

  // 返回找到的组合
  return result.length > 0 ? result[result.length - 1] : [];
}

async function getCfg() {
  const res = await cfgList();
  console.log(res);
  updateFormData.loginTime = res.result.data.syslog;
  let ip = res.result.data.syslog.ip;
  let ips = ip.split(";");
  if (ips.length) {
    updateFormData.logCfg = [];
    for (let i = 0; i < ips.length; i++) {
      let row = ips[i].split(":");
      updateFormData.logCfg.push({
        ip: row[0],
        port: row[1],
        id: generateUUID()
      });
    }
  }
  updateFormData.state = Boolean(Number(res.result.data.syslog.state));
  if (res.result.data.syslog.type) {
    let arr = findCombinationForSum([1, 4, 56], res.result.data.syslog.type - 2);
    let list = [];
    if (arr.length > 0) {
      list = [...new Set(arr)];
    }
    console.log("list", list);
    updateFormData.type = list;
  } else {
    updateFormData.type = [];
  }
  if (res.result.data.syslog.orglog_sentry) {
    updateFormData.type.push(0);
  }
}

async function setCfg() {
  await updateFormRef.value.validate();
  let count = 0;
  updateFormData.type.forEach(item => {
    count += item;
  });
  console.log(updateFormData.type);
  let orglog_sentry = 0;
  let orglog_iptable = 0;
  let orglog_hserver = 0;
  if (updateFormData.type.includes(0)) {
    orglog_sentry = 15;
    orglog_iptable = 7;
    orglog_hserver = 3;
  }
  await cfgSetSyslog({
    syslog: JSON.stringify({
      state: Number(updateFormData.state),
      ip: updateFormData.logCfg.map(item => `${item.ip}:${item.port}`).join(";"),
      orgflow_proto: 0,
      orgflow_flags: 0,
      type: count ? count + 2 : 0,
      orglog_sentry,
      orglog_iptable,
      orglog_hserver
    })
  });
  ElMessage.success("更新成功");
  getCfg();
}

onMounted(() => {
  setTimeout(() => {
    getCfg();
  }, 1200);
});

function add() {
  if (updateFormData.logCfg.length >= 3) {
    ElMessage.warning("至多新增3项");
    return;
  }
  updateFormData.logCfg.push({
    ip: "",
    port: "",
    id: generateUUID()
  });
}

function remove(id) {
  updateFormData.logCfg.splice(
    updateFormData.logCfg.findIndex(item => item.id === id),
    1
  );
}

const isEdit = ref(false);
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header h-box justify-between">
        <span>Syslog</span>
        <div class="card-footer h-box justify-end">
          <el-checkbox :disabled="!isEdit" v-model="updateFormData.state"></el-checkbox>

          <base-button class="mg-l-lg" @click="getCfg" type="refresh_icon_text"></base-button>
          <base-button :disabled="!isEdit" @click="setCfg" type="save_icon"></base-button>
          <base-button v-if="!isEdit" @click="isEdit = !isEdit" type="edit_text" class="mg-l-sm"></base-button>
          <base-button v-else @click="isEdit = !isEdit" type="cancel_icon" class="mg-l-sm"></base-button>
        </div>
      </div>
    </template>

    <el-form
      style="height: 149px"
      :disabled="!isEdit || !updateFormData.state"
      ref="updateFormRef"
      :model="updateFormData"
      :rules="updateFormRules"
      label-width="95px"
      label-suffix="："
    >
      <el-form-item label="发送地址" prop="logCfg">
        <div class="h-box mg-b-sm" v-for="(item, index) in updateFormData.logCfg" :key="item.id">
          <el-input v-model="item.ip" style="width: 130px" placeholder="IP"></el-input>
          :
          <el-input v-model="item.port" style="width: 80px" placeholder="端口"></el-input>
          <el-icon @click="add" class="cursor-pointer mg-l-sm">
            <CirclePlus />
          </el-icon>
          <el-icon v-if="updateFormData.logCfg.length != 1" @click="remove(item.id)" class="cursor-pointer mg-l-sm">
            <Remove />
          </el-icon>
        </div>
        <el-input type="hidden" :model-value="updateFormData.logCfg"></el-input>
      </el-form-item>
      <el-form-item label="日志类型" prop="type">
        <div class="h-box mg-b-sm">
          <el-checkbox-group v-model="updateFormData.type">
            <el-checkbox :value="1" label="设备信息"></el-checkbox>
            <el-checkbox :value="4" label="告警封堵"></el-checkbox>
<!--            <el-checkbox :value="56" label="攻击日志"></el-checkbox>-->
<!--            <el-checkbox :value="0" label="会话日志"></el-checkbox>-->
          </el-checkbox-group>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style lang="scss" scoped></style>
